var _that;
var app = getApp();
var goodsPerHgt = 80;
var _cartype;

function carInit(target,cartype='bread') {
  _that = target;
  _cartype = cartype;
  _that.setData({
    needshow: false,
    carscrollhgt: 0,
    goodslist:{}
  });

  _that.animation = wx.createAnimation({
    duration: 300,
    timingFunction: 'ease-out',
    // 延迟多长时间开始
    delay: 0,
    transformOrigin: 'left bottom 0',
    success: function (res) {
      console.log(res)
    }
  });

  loadCarData();
}

function showDetail() {
  // console.log('showcar');
  if (_that.data.totalcount <= 0) {
    return;
  }
  var topoffset = _that.data.carscrollhgt;
  _that.setData({
    needshow: true,
    carTopOffset: topoffset
  });

  
  _that.animation.top(0).step()

  _that.setData({
    car_amt: _that.animation.export()
  });
}

function closeDetail() {
  _that.setData({
    needshow: false
  });
}

function update() {

}

function submitOrder(orderinfo) {
  wx.navigateTo({
    url: '../neworder/neworder?type='+_cartype,
  });
}

function handleCount(e) {
  var options, goodsid;
  if(e.currentTarget){
    options = parseInt(e.currentTarget.dataset.options);
    goodsid = e.currentTarget.dataset.goodsid;
  }
  else{
    options = e.options;
    goodsid = e.goodsid;
  }

  var goodslist = _that.data.goodslist;
  var totalcount = parseInt(_that.data.totalcount);
  var totalprice = parseFloat(_that.data.totalprice);
  if (options == '1') {
    totalcount += 1;
    totalprice += 19.99;
    goodslist.push({
      name: '甜杏软欧',
      price: '19.99',
      count: '1',
      img: '../imgs/index/goods6.jpg'
    });
  }
  else {
    if (totalcount - 1 < 0) {

    }
    else {
      totalcount -= 1;
      totalprice -= 19.99;
      goodslist.pop();
    }
  }
  totalprice = app.keepTwoDecimalFull(totalprice);
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: goodslist
  });
  adjustHeight();
  if(totalcount == 0){
    _that.setData({
      needshow: false
    });
  }
}

module.exports = {
  init: carInit,
  showCar: showDetail,
  closeCar: closeDetail,
  update: update,
  submitOrder: submitOrder,
  handleCount: handleCount
}

//------以下方法不外调
function loadCarData() {
  var totalcount = 0;
  var totalprice = 0.00;
  var goodslist = [];
  if (_that.data.count) {
    count = parseInt(_that.data.count);
  }
  if (_that.data.totalprice) {
    count = parseFloat(_that.data.totalprice);
  }
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: goodslist
  });
  adjustHeight();
}

function adjustHeight() {
  var hgt = _that.data.goodslist.length * goodsPerHgt;
  var win_hgt = wx.getSystemInfoSync().windowHeight;
  if (hgt > win_hgt * 0.5) {
    hgt = win_hgt * 0.5;
  }
  hgt += 70;
  _that.setData({
    carscrollhgt: hgt,
    goodsPerHgt: goodsPerHgt
  });
}
